package com.springboot.cloud.common.core.oss;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.green.model.v20180509.ImageSyncScanRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.springboot.cloud.common.core.constant.Constant;
import com.springboot.cloud.common.core.util.DateUtils;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * Created by yh on 2020/11/29.
 * oss 鉴黄服务
 */
@Configuration
@Component
@Slf4j
public class OssScanUtil {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.regionId}")
    private String regionId;

    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.accessKeySecret}")
    private String secretAccessKey;



    protected static String getDomain(String regionId) {
        if ("cn-shanghai".equals(regionId)) {
            return "green.cn-shanghai.aliyuncs.com";
        }

        if ("cn-beijing".equals(regionId)) {
            return "green.cn-beijing.aliyuncs.com";
        }

        if ("ap-southeast-1".equals(regionId)) {
            return "green.ap-southeast-1.aliyuncs.com";
        }

        if ("us-west-1".equals(regionId)) {
            return "green.us-west-1.aliyuncs.com";
        }

        return "green.cn-shanghai.aliyuncs.com";
    }

    public boolean ImageSyncScanRequest(String url) {

        boolean result = false;
        try {

            log.info("鉴黄 regionId = [" + regionId + "]");
            log.info("鉴黄 accessKeyId = [" + accessKeyId + "]");
            log.info("鉴黄 accessKeySecret = [" + secretAccessKey + "]");

            IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secretAccessKey);
            DefaultProfile.addEndpoint(endpoint, regionId, "Green", getDomain(regionId));
            IAcsClient client = new DefaultAcsClient(profile);

            ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
            imageSyncScanRequest.setAcceptFormat(FormatType.JSON); // 指定api返回格式
            imageSyncScanRequest.setMethod(com.aliyuncs.http.MethodType.POST); // 指定请求方法
            imageSyncScanRequest.setEncoding("utf-8");
            imageSyncScanRequest.setRegionId(regionId);


            List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();
            Map<String, Object> task = new LinkedHashMap<String, Object>();
            task.put("dataId", UUID.randomUUID().toString());
            task.put("url", url);
            task.put("time", new Date());

            tasks.add(task);
            JSONObject data = new JSONObject();
            /**
             * porn: 色情
             * terrorism: 暴恐
             * qrcode: 二维码
             * ad: 图片广告
             * ocr: 文字识别
             */
            data.put("scenes", Arrays.asList("porn", "terrorism"));
            data.put("tasks", tasks);

            imageSyncScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);

            /**
             * 请务必设置超时时间
             */
            imageSyncScanRequest.setConnectTimeout(3000);
            imageSyncScanRequest.setReadTimeout(10000);

            HttpResponse httpResponse = client.doAction(imageSyncScanRequest);

            if (httpResponse.isSuccess()) {
                JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
                System.out.println(JSON.toJSONString(scrResponse, true));
                if (200 == scrResponse.getInteger("code")) {
                    JSONArray taskResults = scrResponse.getJSONArray("data");
                    for (Object taskResult : taskResults) {
                        if (200 == ((JSONObject) taskResult).getInteger("code")) {
                            JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
                            for (Object sceneResult : sceneResults) {
                                String scene = ((JSONObject) sceneResult).getString("scene");
                                String suggestion = ((JSONObject) sceneResult).getString("suggestion");
                                //根据scene和suggetion做相关的处理
                                //do something
                                log.info("鉴黄 args = [" + scene + "]");
                                log.info("鉴黄结果 args = [" + suggestion + "]");
                                if ("pass".equalsIgnoreCase(suggestion)) {
                                    result = false;
                                } else if ("review".equalsIgnoreCase(suggestion)) {
                                    result = false;
                                } else if ("block".equalsIgnoreCase(suggestion)) {
                                    result = true;
                                    return result;
                                }
                            }
                        } else {
                            System.out.println("task process fail:" + ((JSONObject) taskResult).getInteger("code"));
                        }
                    }
                } else {
                    System.out.println("detect not success. code:" + scrResponse.getInteger("code"));
                }
            } else {
                System.out.println("response not success. status:" + httpResponse.getStatus());
            }
        } catch (Exception e) {

        }
        return result;
    }

}
